<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 17:38
 */

namespace app\common\model;

use app\common\cachemodel\MapLinePlanetInfo;
use app\common\cachemodel\MapRecodeBack;
use app\common\cachemodel\MapUnlockResult;
use app\common\cachemodel\zl4\Zl4UserDataTypeStatus;
use app\common\lib\astrolog\Acg;

/**
 * Class Map
 * @package app\common\model
 */
class Map extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_map';

    protected $calculationDay = 180;//重新计算的时间

    protected static $getRecodeUnlockLinesData = null;

    /**
     * 检测该经纬度用户是否已经收藏
     * @param array $map
     * latitude float must 纬度
     * longitude float must 经度
     * uid int must 用户id
     * rid int must 档案id
     * @return array
     */
    public function checkCollectStatus($map = [])
    {
        $result = [];
        try
        {
            $data = $this->alias('m')
                ->join('wechat_backup_07_18_14_43_00.app_map_collect mc', 'mc.mid=m.id')
                ->where([
                    'm.latitude' => $map['latitude'],
                    'm.longitude' => $map['longitude']
                ])
//                ->whereBetween('m.latitude', '')
                ->where(['mc.uid' => $map['uid'], 'mc.rid' => $map['rid']])
                ->findOrFail();
            $result['is_collect'] = true;
            $result['collect_id'] = $data['id'];
        }
        catch (\Exception $e)
        {
            $result['is_collect'] = false;
            $result['collect_id'] = 0;
        }
        return $result;
    }

    /**
     * 检测档案已解锁的地图线条或命运之城
     * @param $recode
     * @param bool $getPlanetsInfo 获取行星线的数据
     * @return array
     * 日,月,水,金,火,木,土,天,海,冥,北交,命运之城
     * 0表示未解锁 1表示已解锁
     * @throws \app\common\lib\exception\ApiException
     */
    public function getRecodeUnlockLines($recode, $getPlanetsInfo = false): array
    {
        $dataKey = $recode['id'] . ':' . ($getPlanetsInfo ? 1 : 0);
        if (isset(self::$getRecodeUnlockLinesData[$dataKey]))
        {
            return self::$getRecodeUnlockLinesData[$dataKey];
        }
        //获取用户当前已解锁的数据
        $unlockIds = (new MapUnlockResult())->getUnlockIdsFromCache(3, $recode['id']);
        $unlockInfos = (new MapUnlockResult())->batchGetInfoByIds($unlockIds, ['id', 'gid', 'status', 'rid_back', 'line_planet_info_id', 'last_calculation_time']);
        $maxData = $this->getNewCityUnlockData($unlockInfos);
        $unlockInfos = array_column($unlockInfos, null, 'gid');
        $unlockGids = array_keys($unlockInfos);
        $arr['lines'] = [
            'data' => '000000011000',// 默认 开启天海
            'status' => 0,//0=>最新逻辑，无需更新，1=》逻辑需要更新，2=》逻辑计算中
        ];
        $arr['planets'] = [];
        $arr['recalculation_info'] = [];
        if ($unlockInfos)
        {
            //获取用户当前已解锁的命格线 string 12位
            if (!empty($unlockInfos[105]))
            {
                if ($unlockInfos[105]['status'] == 1)
                {
                    $arr['lines']['status'] = 2;
                }
                $arr['lines']['data'] = '111111111111';
            } elseif (!empty($unlockInfos[19]))
            {
                // 旧版打包解锁幸运之城
                if ($unlockInfos[19]['status'] == 1)
                {
                    $arr['lines']['status'] = 2;
                }
                $arr['lines']['data'] = '111111111111';
            } else
            {
                if (!empty($unlockInfos[103]))//命格线打包解锁
                {
                    $arr['lines']['data'] = '111111111110';
                } else
                {
                    foreach ($unlockInfos as $unlockItem)
                    {
                        $arr['lines']['data'][$unlockItem['gid'] - 7] = 1;// 太阳线起始gid为7
                    }
                }
                // 单独解锁命运之城
                if (!empty($unlockInfos[18]))
                {
                    // $unlockInfos status=1 计算中  status=2 计算完成
                    if ($unlockInfos[18]['status'] == 1)
                    {
                        $arr['lines']['status'] = 2;
                    }
                    $arr['lines']['data'][11] = 1;// 太阳线起始gid为7
                }
            }
            if ($maxData)
            {
                $arr['recalculation_info'] = $this->diffRecodeInfo($maxData, $recode);
                $arr['planets'] = json_decode((new MapLinePlanetInfo())->getInfoById($maxData['line_planet_info_id']), true);//获取客户端绘制命格线所需的数据
            } else
            {
                $arr['planets'] = (new Acg())->getPlanetInfo($recode);// 计算客户端绘制命格线所需的数据
            }
        } elseif ($getPlanetsInfo)
        {
            $arr['planets'] = (new Acg())->getPlanetInfo($recode);// 计算客户端绘制命格线所需的数据
        }
        //0=>最新逻辑，无需更新，1=》逻辑需要更新，2=》逻辑计算中
//        if ($arr['lines']['status'] === 2)
//        {
//            $arr['lines']['data'] = '000000011000';
//        }

        //旧版购买了打包解锁,提示弹窗
        if (in_array(19, $unlockGids, false))
        {
            $unlockGids = array_merge($unlockGids, [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 104]);
            $unlockGids = array_unique($unlockGids);
        }
        //幸运之城打包解锁2
        if (in_array(105, $unlockGids, false))
        {
            $goodsGidConfig = config('goods');
            $unlockGids = $goodsGidConfig['acg_id'];
        }
        $arr['unlock_gids'] = $unlockGids;
        $cityScoreStatus = $this->getCityScoreUnlockStatus($unlockGids);
        $lineStatus = $this->getLineUnlockStatus($unlockGids);
        $fateCityStatus = $this->getFateCityUnlockStatus($unlockGids);
        $cityDetailStatus = $this->getAnywhereUnlockStatus($unlockGids);

        if ($cityScoreStatus && $lineStatus && $fateCityStatus && $cityDetailStatus)
        {
            $arr['pack_and_unlock'] = null;
        } else
        {
            $arr['pack_and_unlock'] = [
                'title' => '- 幸运地图全功能 -',
                'list' => [
                    0 => [
                        'title' => '9大维度的指数排行',
                        'status' => $cityScoreStatus
                    ],
                    1 => [
                        'title' => '11条命格线全解锁',
                        'status' => $lineStatus
                    ],
                    2 => [
                        'title' => '命运之城全解锁',
                        'status' => $fateCityStatus
                    ],
                    3 => [
                        'title' => '任意地点的具体影响全解锁',
                        'status' => $cityDetailStatus
                    ],
                ]
            ];
        }
        $arr['tab_list'] = [
            [
                'icon' => 'https://oss.goddessxzns.com/test/map/city_score/city_score_icon.png',
                'name' => '城市排行',
                'type' => 2,
                'is_select' => 1,
            ],
            [
                'icon' => 'https://oss.goddessxzns.com/test/map/city_score/line_icon.png',
                'name' => '命格线',
                'type' => 1,
                'is_select' => 0,
            ],
            [
                'icon' => 'https://oss.goddessxzns.com/test/map/city_score/fate_city_icon.png',
                'name' => '命运之城',
                'type' => 3,
                'is_select' => 0,
            ]
        ];

        self::$getRecodeUnlockLinesData[$dataKey] = $arr;
        return $arr;
    }

    /**
     * 获取最新的命运之成解锁数据
     * @param $unlockInfos
     * @return array
     */
    public function getNewCityUnlockData($unlockInfos)
    {
        $max_key = NULL;
        $max_data = [];
        foreach ($unlockInfos as $key => $item)
        {
            if (in_array($item['gid'], [18, 19, 105], false))
            {
                if (!isset($max_key) || $key > $max_key)
                {
                    $max_key = $key;
                    $max_data = $item;
                }
            }
        }
        return $max_data;
    }

    /**
     * 获取解锁档案和当前档案的对比结果
     * @param array $unlockInfo 解锁信息
     * @param array $recode 解锁档案
     * @return array
     * @throws \Exception
     */
    public function diffRecodeInfo($unlockInfo, $recode)
    {
        //判断解锁档案和当前档案信息
        $recodeBack = json_decode((new MapRecodeBack())->getInfoById($unlockInfo['rid_back']), true);
        $recodeInfoStr = (new \app\common\cachemodel\Recode())->getRecodeInfoStr($recode);
        $backRecodeInfoStr = (new \app\common\cachemodel\Recode())->getRecodeInfoStr($recodeBack);
        //若当前计算中则不提示档案修改的信息
        if ($recodeInfoStr != $backRecodeInfoStr)
        {
            $calculationTime = time() - $unlockInfo['last_calculation_time'];
            if ($calculationTime > ($this->calculationDay * 86400))
            {
                $recalculation_info = [
                    'btn_msg' => '档案信息已修改，点击刷新地图',
                    'title' => '是否重新计算地图信息',
                    'status' => 3,
                    'content' => "档案信息发生修改后，每{$this->calculationDay}天内仅可免费重新计算一次，且此操作不可逆"
                ];
            } else
            {
                $surplusTime = 180 - ((int)($calculationTime / 86400));
                $recalculation_info = [
                    'btn_msg' => '档案信息发生修改，信息可能失准',
                    'title' => '重新计算地图信息',
                    'status' => 4,
                    'content' => "每180天内仅可免费重新计算一次地图信息，你已重新计算过地图信息，请于{$surplusTime}天后再次尝试重新计算"
                ];
            }
        }
        return $recalculation_info ?? [];
    }

    /**
     * 获取命格线列表
     * @param $header
     * @param $lines
     * @return array
     */
    public function getLineList($header, $lines, bool $filterFatelct = false)
    {
        if ($header->is_apple_pay)
        {
            $acg_goods = $header->apple_goods['acg_goods'];
        } else
        {
            $acg_goods = (new Goods())->getGoodsForACG();
        }

        // 从配置文件中加载相关配置
        $config = config('map');

        $line_list = [];// 所有命格线商品

        foreach ($acg_goods as $ag)
        {
            if ($ag['id'] > 18)
            {
                continue;
            }// 只需要11条线的数据

            if ($filterFatelct && $ag['id'] == 18)
            {
                continue;
            }

            $discount = (float)$ag['discount'];// 折扣

            $price = $discount ? $ag['or_prize'] * $discount : $ag['now_prize'];// 计算实际价格

            //商品折扣活动
            $activeDiscount = active($ag['id']);
            if ($activeDiscount['discount'])
            {
                $price *= $activeDiscount['discount'];
            }

            $is_unlock = $lines[$ag['id'] - 7] == 1;

            $tmp = [
                'gid' => $ag['id'],
                'name' => $ag['name'],
                'price' => sprintf('%.2f', $price),
                'icon' => $config['lines_icon'][$ag['id']],
                'description' => $config['lines_title'][$ag['id']],
                'color' => $config['lines_color'][$ag['id']],
                'is_unlock' => $is_unlock,
                'pid' => $config['pid'][$ag['id']],
                'planet' => $config['planet'][$ag['id']],
                'point_title' => $config['point_title'][$ag['id']],
                'point_des' => $config['point_des'][$ag['id']],
            ];

            if ($ag['id'] == 18)
            {
                $tmp['description'] = '这是在中国境内，对你生活起居某方面最为有利的大城市，能对你不同方面起到良好的改善作用。（此处只有国内一、二、三线城市，后续会持续更新国内其他小城市和国外城市的计算，所以你的命运之城可能会随着升级会有改变。）解锁后对每一座命运之城都有详细解读。';
            }

            $line_list[] = $tmp;
        }
        return resort($line_list, 'is_unlock');// 布尔值进行排序，暂未发现问题????
    }

    /**
     * 获取命格线全解锁状态
     * @param $unlockGids
     * @return int
     */
    public function getLineUnlockStatus($unlockGids)
    {
        $gidsConfig = config('goods');
        sort($unlockGids);
        $acgLineId = array_diff($gidsConfig['acg_line_id'], [14, 15]);
        return array_intersect([19, 103, 105], $unlockGids) ? 1 : ($acgLineId == array_intersect($acgLineId, $unlockGids) ? 1 : 0);
    }

    /**
     * 获取城市排行全解锁状态
     * @param $unlockGids
     * @return int
     */
    public function getCityScoreUnlockStatus($unlockGids)
    {
        $gidsConfig = config('goods');
        sort($unlockGids);
        return array_intersect([19, 104, 105], $unlockGids) ? 1 : ($gidsConfig['acg_city_id'] == array_intersect($gidsConfig['acg_city_id'], $unlockGids) ? 1 : 0);
    }

    /**
     * 获取命运之城解锁状态
     * @param $unlockGids
     * @return int
     */
    public function getFateCityUnlockStatus($unlockGids)
    {
        sort($unlockGids);
        return array_intersect([18, 19, 105], $unlockGids) ? 1 : 0;
    }

    /**
     * 获取任意地点具体影响解锁状态
     * @param $unlockGids
     * @return int
     */
    public function getAnywhereUnlockStatus($unlockGids)
    {
        sort($unlockGids);
        return array_intersect([102, 105], $unlockGids) ? 1 : 0;
    }
}
